/**
 * 
 */
package de.fsujena.chat_pi.user;

import java.io.Serializable;

import org.jasypt.util.password.*;

/**
 * A class representing a user and storing relevant informations. The password is stored 
 * as a SHA-256-hash for security reasons.
 * 
 * @author Erik Hebestreit
 * @see UserManagemant
 */
public class User implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4343343581995365352L;
	
	public String name;
	private String passwordHash;
	
	public enum ROLE {STANDARD, MODERATOR, ADMIN, }	
	public ROLE role = ROLE.STANDARD; 
	
	public enum STATUS {NORMAL, BANNED, }
	public STATUS status = STATUS.NORMAL;

	/**
	 * initialize a new user with name and password
	 * 
	 * @param name name of the user
	 * @param password password of the user (private)
	 */
	public User(String name,String password) {
		// initialize password encryptor
		StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
		
		this.name = name;
		// save password after converting to a SHA-256-hash
		this.passwordHash = passwordEncryptor.encryptPassword(password);
	}
	
	/**
	 * set a new name for the user
	 * 
	 * @param name new name for user
	 * @return <b>true</b> if successful
	 */
	public Boolean setName(String name) {
		this.name = name;
		return true;
	}
	
	/**
	 * set a new password
	 * 
	 * @param oldPassword current password to verify permission of changing password
	 * @param newPassword password to be set
	 * @param newPasswordRetyped retyped new password, to check for typos
	 * @return 0 states a successful reseting of the password, 1 states a wrong old
	 * 			password, 2 states a mismatch between the new password and the retyped 
	 * 			new password
	 */
	public boolean setPassword(String oldPassword,
			String newPassword) {
		// initialize password encryptor
		StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
		
		if(!checkPassword(oldPassword))
			return false; // returns 1 if the old password is not right
		
		this.passwordHash = passwordEncryptor.encryptPassword(newPassword);
		return true;
	}
	
	/**
	 * checks if the input value matches the stored password of the user
	 * 
	 * @param passwordToCheck password to be checked
	 * @return <b>true</b> if password matches the stored one, <b>false</b> if there 
	 * 			is a mismatch
	 */
	public Boolean checkPassword(String passwordToCheck) {
		// initialize password encryptor
		StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
		
		return passwordEncryptor.checkPassword(passwordToCheck, this.passwordHash);
	}
}
